<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 矿机管理
 */
namespace app\settle\model;

use app\settle\model\Model;
use Mscore\Core\Redis;

class Zeroorder extends Model{
    
    private $orderlog = 'pro_zeroorderlog';
    private $account = 'user_account';
    private $order = 'pro_zeroorder';
    private $hashfix = '';
    private $key = '';

    public function __construct()  
    {    
        $this->hashfix=config('redis.redis_db.db_hashfix');
        $this->key = config('zerocontrol.order');
    }  

    /**
     * 列表
     * @param array $list 
     * @param array $where 
     */ 
    public function list($where=null,$page=1,$page_size=10){
        //矿机列表
        $list['datalist']= Model::name($this->order)
            ->alias('a')
            ->join($this->account.' b','a.aid=b.aid','left')
            ->field('a.*, b.username, b.realname')
            ->where($where)
            ->limit(($page-1)*$page_size,$page_size)
            ->order('createtime desc')
            ->select()
            ->toArray();
        foreach ($list['datalist'] as $key => $value) {
            $data = Redis::exec('hget',[$this->hashfix.$this->key,$value['id']]);
            switch ($value['status']) {
                case 1:
                    if(!empty($data)){
                        $data=json_decode($data,true);
                        $list['datalist'][$key]['profitrate']=isset($data['profitrate'])?$data['profitrate']:0;
                        $list['datalist'][$key]['money']=isset($data['money'])?$data['money']:0;
                        $list['datalist'][$key]['win']=isset($data['win'])?$data['win']:0;
                        $list['datalist'][$key]['rstatus']=0; 
                    }else{
                        $list['datalist'][$key]['rstatus']=1; 
                    }
                    break;
                
                case 2:
                    if(!empty($data)){
                        $data=json_decode($data,true);
                        $list['datalist'][$key]['profitrate']=isset($data['profitrate'])?$data['profitrate']:0;
                        $list['datalist'][$key]['money']=isset($data['money'])?$data['money']:0;
                        $list['datalist'][$key]['win']=isset($data['win'])?$data['win']:0;
                        $list['datalist'][$key]['rstatus']=1; 
                    }else{
                        $list['datalist'][$key]['rstatus']=0; 
                    }
                    break;
            }
        }
        $cmf_arr = array_column($list['datalist'], 'rstatus');//抽取排序字段
        array_multisort($cmf_arr, SORT_DESC, $list['datalist']); //根据字段排序SORT_ASC - 默认。按升序排列 (A-Z)；SORT_DESC - 按降序排列 (Z-A)。
        //数据总数
        $list['total']=Model::name($this->order)
            ->alias('a')
            ->join($this->account.' b','a.aid=b.aid','left')
            ->where($where)
            ->count('id');
        return $list;
    }

    /**
     * 信息
     * @param array $info 
     * @param array $where 
     */ 
    public function info($id=null){  
        $info = Model::name($this->order)
           ->alias('a')
           ->join($this->account.' b','a.aid=b.aid','left')
           ->field('a.*, b.realname,b.mobile,b.username,b.email')
           ->where(['id'=>$id])
           ->find();
        $data = Redis::exec('hget',[$this->hashfix.$this->key,$id]);
        if(!empty($data)){
            $info['rstatus']=1;
        }else{
            $info['rstatus']=0;
        }
        switch ($info['status']) {
            case 1:
                if(!empty($data)){
                    $info['rstatus']=0;
                }else{
                    $info['rstatus']=1;
                }
                break;    
            case 2:
                if(!empty($data)){
                    $info['rstatus']=1;
                }else{
                    $info['rstatus']=0; 
                }
                break;
        }
        if(isset($info['factor'])&&!empty($info['factor'])){
            $info['factor'] = json_decode($info['factor'],true);
        }
        return $info;
    }

    /**
     * 信息
     * @param array $info 
     * @param array $where 
     */ 
    public function userinfo($where=null){  
         return Model::name($this->account)
           ->where($where)
           ->value('aid');
    }

    /**
     * 总计信息
     * @param array $suminfo 
     * @param array $where 
     */ 
    public function suminfo($where=null,$field='a.*'){  
         return Model::name($this->order)
           ->alias('a')
           ->field($field)
           ->where($where)
           ->find();
    }
    
    /**
     * 信息
     * @param array $info 
     * @param array $where 
     */ 
    public function infolog($where=null,$field='*'){  
         return Model::name($this->orderlog)
           ->field($field)
           ->where($where)
           ->find();
    }

    /**
     * 信息
     * @param array $info 
     * @param array $where 
     */ 
    public function infologlist($where=null,$field='*'){  
         return Model::name($this->orderlog)
           ->field($field)
           ->where($where)
           ->select()
           ->toArray();
    }


    /**
     * 保存
     * @param array $save 
     * @param array $where 
     */ 
    public function save($data=[]){
        $factor=0;$type=0;
        if(!empty($data['factor']['profitrate'])){
            $factor=$data['factor']['profitrate']*$data['factor']['type'];
            $type = $data['factor']['type'];
        }
        $data  = [
            'id'=>$data['id'],
            'factor'=>json_encode($data['factor'])
        ];
        
        switch (true) {
            case isset($data['id'])&&!empty($data['id']):
                $id=$data['id']; unset($data['id']);
                Model::name($this->order)->where('id=' . $id)->update($data);
                $data = Redis::exec('hget',[$this->hashfix.$this->key,$id]);
                if(isset($data)&&!empty($data)){
                    $data = json_decode($data,true);
                }else{
                    $data = Model::name($this->order)->where('id=' . $id)->find();
                }
                $data['factor']=$factor;
                if($type==0){
                   unset($data['factor']);
                }
                Redis::exec('hset',[$this->hashfix.$this->key,$id,json_encode($data)]);
                return true;
                break;
            
            default:
                return false;
                break;
        }
    }

    /**
     * 保存
     * @param array $save 
     * @param array $where 
     */ 
    public function edit($data=[]){
        $data  = [
            'id'=>$data['id'],
            'profitrate'=>$data['profitrate'],
            'money'=>$data['money'],
            'aid'=>$data['aid'],
            'status'=>$data['status'],
        ];
        $id=$data['id']; unset($data['id']);
        switch ($data['status']) {
            case 1:
                $params=Model::name($this->order)->where('id=' . $id)->field('*')->find();
                $params=[
                    'id'=>$id,
                    'order_no'=>$params['order_no'],
                    'type'=>$params['type'],
                    'aid'=>$params['aid'],
                    'pid'=>$params['pid'],
                    'price'=>$params['price'],
                    'bond'=>$params['bond'],
                    'puffs'=>$params['puffs'],
                    'proid'=>$params['proid'],
                    'proname'=>$params['proname'],
                    'procode'=>$params['procode'],
                    'updown'=>$params['updown'],
                    'buyprice'=>$params['buyprice'],
                    'sx_fee'=>$params['sx_fee'],
                    'status'=>$params['status'],
                    'profitrate'=>$data['profitrate'],
                    'money'=>$data['money'],
                    'createtime'=>$params['createtime']
                ];
                Redis::exec('hset',[$this->hashfix.$this->key,$id,json_encode($params)]);
                break;
            
            case 2:
                Model::name($this->order)->where('id=' . $id)->update($data);
                Redis::exec('hdel',[$this->hashfix.$this->key,$id]);
                Redis::exec('hdel',[$this->hashfix.$this->key.$data['aid'],$id]);
                break;
        }
        return true;
    }

    /**
     * 重算
     * @param array $save 
     * @param array $where 
     */ 
    public function resettle($data=[]){
        $id=$data['id'];$ratio=$data['ratio'];
        unset($data);
        switch (true) {
            case isset($id)&&!empty($id):
                $data = Model::name($this->order)->where('id=' . $id)->field('*')->find();
                $beatpoint = Model::name('pro_zerorate')->where('id=' . $data['proid'])->value('beatpoint');
                $beatpoint = !empty($beatpoint)?json_decode($beatpoint,true):[];
                $rands=isset($beatpoint['rands'])&&$beatpoint['rands']>0?$beatpoint['rands']:1;
                unset($beatpoint);
                $symbol=$data['win']==1?1:-1;
                $profitrate = $ratio * $symbol * (abs($data['sellprice']-$data['buyprice'])/$rands)/100;
                $money=$data['bond']+$data['price']*$profitrate/100;
                $user=Model::name($this->account)->where('aid='.$data['aid'])->field('amount,giftamount')->find();
                //恢复用户金额
                switch ($data['type']) {
                    case 1:
                        if($data['money']>0){
                            $amount=$user['amount']-$data['money']+$data['bond']; 
                        }else{
                            $amount=$user['amount']+$data['bond']; 
                        }
                        Model::name($this->account)->where('aid='.$data['aid'])->update(['amount'=>$amount]);
                        break;
                    default:
                        if($data['money']>0){
                            $amount=$user['giftamount']-$data['money']+$data['bond']; 
                        }else{
                            $amount=$user['giftamount']+$data['bond']; 
                        }
                        Model::name($this->account)->where('aid='.$data['aid'])->update(['giftamount'=>$amount]);
                        break;
                }
                $datalog = [
                    'orderid'=>$data['id'],
                    'proid'=>$data['proid'],
                    'buyprice'=>$data['buyprice'],
                    'price'=>$data['price'],
                    'bond'=>$data['bond'],
                    'money'=>$money,
                    'puffs'=>$data['puffs']
                ];
                Model::startTrans();
                try {
                    //重寫訂單日志
                    Model::name($this->orderlog)->where('orderid = ' . $id)->delete();
                    for ($i=0; $i <2 ; $i++) { 
                        if($i==0){
                            $datalog['type']=1;
                            $datalog['amount']=$amount;
                            $datalog['backamount']=$datalog['amount']-$data['bond'];
                            $datalog['createtime']=$data['createtime'];
                            $datalog['sellprice']=0;
                            Model::name($this->orderlog)->insert($datalog);   
                        }elseif($i==1){
                            $datalog['type']=2;
                            $datalog['amount']=$datalog['backamount'];
                            if($money>0){
                                $datalog['backamount']=$datalog['amount']+$money;
                            }else{
                                $datalog['backamount']=$datalog['amount'];
                            }
                            $datalog['createtime']=!empty($data['update_time'])?$data['update_time']:date('Y-m-d H:i:s',time());
                            $datalog['sellprice']=$data['sellprice'];
                            Model::name($this->orderlog)->insert($datalog);
                            switch ($data['type']) {
                                case 1:
                                    Model::name($this->account)->where('aid='.$data['aid'])->update(['amount'=>$datalog['backamount']]);
                                    break;
                                default:
                                    Model::name($this->account)->where('aid='.$data['aid'])->update(['giftamount'=>$datalog['backamount']]);
                                    break;
                            }
                        }
                    };
                    Model::name($this->order)->where('id=' . $id)->update(['ratio'=>$ratio,'profitrate'=>$profitrate,'money'=>$money]);
                    Model::commit();
                    return true; 
                } catch (Exception $e) {
                    Model::rollback();
                    return false;
                }
                return false;
                break;
            
            default:
                return false;
                break;
        }
    }

    /**
     * 删除
     * @param array $del 
     * @param array $where 
     */
    public function del($id=null){
     //删除
        if ($id) {
            Model::name($this->order)->where('id='.$id)->update(['dels'=>1]);
            return true;
        }
        return false;
    }

}
